package com.four.order.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.four.order.config.PaymentConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gs
 * @since 2021-12-24
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @GetMapping("toPay")
    public String toPay(HttpServletRequest request) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(PaymentConfig.gatewayUrl, PaymentConfig.app_id, PaymentConfig.merchant_private_key, "json", PaymentConfig.charset, PaymentConfig.alipay_public_key, PaymentConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(PaymentConfig.return_url);
        alipayRequest.setNotifyUrl(PaymentConfig.notify_url);

        //todo 根据当前用户的订单 查出订单号 支付价格  等信息

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String("123456");
        //付款金额，必填
        String total_amount = new String("100.00");
        //订单名称，必填
        String subject = new String("狗震牌芒果");
        //商品描述，可空
        String body = new String("芒果六连鞭");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出out.println(result);
        // 把字符串返回给浏览器 他就会自动跳转到支付宝页面
        return result;
    }

}
